import machine
import time

# NTC配置
NTC_PIN = 0  # GPIO0 (ADC1_CHANNEL_0)
VREF = 3.3   # 参考电压
R_REF = 10000  # 10K参考电阻

# NTC温度表: -30C 到 110C 对应的电阻值 (141个点)
ntc_val = [
    177000, 166400, 156500, 147200, 138500, 130400, 122900, 115800, 109100, 102900,
    97120, 91660, 86540, 81720, 77220, 72980, 69000, 65260, 61760, 58460,
    55340, 52420, 49660, 47080, 44640, 42340, 40160, 38120, 36200, 34380,
    32660, 31040, 29500, 28060, 26680, 25400, 24180, 23020, 21920, 20880,
    19900, 18970, 18090, 17260, 16460, 15710, 15000, 14320, 13680, 13070,
    12490, 11940, 11420, 10920, 10450, 10000, 9574, 9166, 8778, 8408,
    8058, 7722, 7404, 7098, 6808, 6532, 6268, 6016, 5776, 5546,
    5326, 5118, 4918, 4726, 4544, 4368, 4202, 4042, 3888, 3742,
    3602, 3468, 3340, 3216, 3098, 2986, 2878, 2774, 2674, 2580,
    2488, 2400, 2316, 2234, 2158, 2082, 2012, 1942, 1876, 1813,
    1751, 1693, 1637, 1582, 1530, 1480, 1432, 1385, 1341, 1298,
    1256, 1216, 1178, 1141, 1105, 1071, 1038, 1006, 975, 945.2,
    916.4, 888.8, 862, 836.4, 811.4, 787.4, 764.2, 741.8, 720.2, 699.4,
    679.2, 659.6, 640.8, 622.6, 605, 588, 571.4, 555.6, 540.2, 525.2, 510.8
]

def setup_adc(pin=None):
    """设置ADC
    
    Args:
        pin: GPIO引脚号，如果为None则使用默认的NTC_PIN
        
    Returns:
        配置好的ADC对象
    """
    # 如果没有提供引脚，使用默认引脚
    if pin is None:
        pin = NTC_PIN
        
    print(f"Setting up ADC on GPIO{pin}...")
    adc = machine.ADC(machine.Pin(pin))
    adc.atten(machine.ADC.ATTN_11DB)  # 11dB衰减，支持0-3.3V
    # ESP32-C3默认12位分辨率
    print("ADC setup completed")
    return adc

def read_voltage(adc, samples=10):
    """读取平均电压值"""
    total = 0
    for _ in range(samples):
        total += adc.read()
        time.sleep(0.001)
    avg_raw = total // samples
    voltage = (avg_raw / 4095) * VREF  # 12位分辨率
    return voltage

def calculate_ntc_resistance(voltage):
    """计算NTC电阻值"""
    # 公式: R_ntc = (Vout * R_ref) / (Vin - Vout)
    if voltage >= VREF:  # 防止除零错误
        return float('inf')
    R_ntc = (voltage * R_REF) / (VREF - voltage)
    return R_ntc

def get_temperature_from_resistance(R_ntc):
    """根据NTC电阻值查找对应的温度"""
    print(f"NTC Resistance: {R_ntc:.2f} ohm")
    
    # 边界检查
    if R_ntc <= ntc_val[-1]:
        return 110
    elif R_ntc >= ntc_val[0]:
        return -30
    
    # 查找最接近的电阻值
    closest_index = 0
    min_diff = float('inf')
    
    for i in range(len(ntc_val)):
        diff = abs(ntc_val[i] - R_ntc)
        if diff < min_diff:
            min_diff = diff
            closest_index = i
    
    # 计算温度
    temperature = closest_index - 30
    # print(f"Closest index: {closest_index}, Temperature: {temperature}°C")
    return temperature
def get_temperature_app(adc):
    # 读取电压
    voltage = read_voltage(adc, 20)  # 20次采样平均
    print(f"\nVoltage: {voltage:.3f}V")
    # 计算NTC电阻
    R_ntc = calculate_ntc_resistance(voltage)
    # 获取温度
    temperature = get_temperature_from_resistance(R_ntc)
    # print(f"Current temperature: {temperature}C")
    

    return temperature
def main():
    """主函数"""
    print("ESP32-C3 NTC Temperature Sensor Test")
    print("==================================")
    
    # 设置ADC - 可以传入不同的引脚号
    # 例如: adc = setup_adc(pin=1)  # 使用GPIO1
    adc0 = setup_adc(0)  # 使用默认引脚
    adc1 = setup_adc(1)  
    
    print("\nStarting temperature measurements...")
    print("Press Ctrl+C to stop")
    
    try:
        while True:
            t1 = get_temperature_app(adc0);
            t2 = get_temperature_app(adc1);
            print(f"t1: {t1:.2f}C, t2: {t2:.2f}C")
            time.sleep(2)
            
    except KeyboardInterrupt:
        print("\nTest stopped by user")
    except Exception as e:
        print(f"Error: {e}")
    finally:
        print("\nTest completed")

if __name__ == '__main__':
    main()